﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AteneoLibriBusinessLogic.Entities;
using System.Globalization;
using System.Threading;
using System.IO;
using AteneoLibri.Utility;
using System.Drawing;
using System.Drawing.Imaging;

namespace AteneoLibri.Account
{
    public partial class InsertBook : System.Web.UI.Page
    {
        string bookImageDirectory = System.Configuration.ConfigurationManager.AppSettings["BookCoverImageDirectory"];
        User user = null;
        Book book = null;
        string idBook = "";

        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (User.Identity.Name.Equals(System.Configuration.ConfigurationManager.AppSettings["AdminName"]))
                {
                    Page.MasterPageFile = "~/BackEnd/BackEndMasterPage.Master";
                }
                else
                {
                    Page.MasterPageFile = "~/Account/NewAccountMasterPage.Master";
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            user = Utility.HttpSessionManager.GetWebUser();

            if (user != null)
            {
                try
                {
                    idBook = Request.QueryString[0];
                }
                catch (Exception) // gestisce la mancanza dell'id book in fase di inserimento
                {

                }

                if (!Page.IsPostBack)
                {


                    // Caricare le università e bindarle nelle dropdown
                    using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                    {


                        List<University> universities = service.getUniversities();

                        ddlUniversity.DataSource = universities;
                        ddlUniversity.DataBind();


                        if (!idBook.Equals("")) // sto modificando un libro
                        {
                            book = service.getBookById(new Guid(idBook));
                            if (book != null)
                            {
                                PageTitle.Text = "Aggiorna libro";
                                // devo bindare sull'interfaccia i campi presi dal book
                                txtTitle.Text = book.Title;
                                txtAuthors.Text = book.Author;
                                txtPublishingHouse.Text = book.PublishingHouse;
                                txtEdition.Text = book.Edition;
                                txtSellingPrice.Text = String.Format("{0:N2}", book.SellingPrice);
                                txtNote.Text = book.Note;

                                // gestire la mancanza dei 2 id relativi all'uni e alla facoltà
                                if (book.UniversityId != null)
                                {
                                    // recupero l'università a partire dell'id
                                    University u = service.getUniversity(book.UniversityId.Value);
                                    string uniName = u.Name;

                                    for (int i = 0; i < universities.Count; i++)
                                    {
                                        if (universities[i].Name == uniName)
                                        {
                                            ddlUniversity.SelectedIndex = i;
                                        }
                                    }

                                    if (book.FacultyId != null)
                                    {

                                        List<Faculty> faculties = service.getFacultiesByUniversity(u.IdUniversity);
                                        ddlFaculty.DataSource = faculties;
                                        ddlFaculty.DataBind();

                                        // recupero la facoltà a partire dall'id
                                        Faculty f = service.getFaculty(book.FacultyId.Value);
                                        string facName = f.Name;

                                        for (int i = 0; i < faculties.Count; i++)
                                        {
                                            if (faculties[i].Name == facName)
                                            {
                                                ddlFaculty.SelectedIndex = i;
                                            }
                                        }
                                    }

                                }

                                // manage cover preview
                                if (book.CoverImage != null) // the image is present
                                {
                                    // show the image                                 
                                    string fileName = Path.GetFileName(book.CoverImage);
                                    PreviewBookImage.ImageUrl = bookImageDirectory + fileName;
                                    pnlPreview.Visible = true;
                                    pnlCoverUpload.Visible = false;
                                }

                                // devo abilitare il pannello di aggiornamento
                                pnlUpdateBook.Visible = true;
                                pnlInsertNewBook.Visible = false;
                            }
                        }

                    }
                }
                lblCurrency.Text = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol;
            
            }
            else
            {
                // Redirect per sessione scaduta
                Response.Redirect("~/Logout.aspx");
            }

        }

        protected void ddlUniversity_SelectedIndexChanged(object sender, EventArgs e)
        {
            ResetFacultyDropDown();

            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                var universityId = ddlUniversity.SelectedItem.Value;
                if (universityId != "0")
                {
                    List<Faculty> faculties = service.getFacultiesByUniversity(new Guid(universityId));
                    ddlFaculty.DataSource = faculties;
                    ddlFaculty.DataBind();
                }
            }
        }

        private void ResetFacultyDropDown()
        {
            ddlFaculty.Items.Clear();
            ddlFaculty.Items.Add("-- Seleziona --");
            ddlFaculty.Items[0].Selected = true;
            ddlFaculty.AppendDataBoundItems = true;
        }

        protected void btnInsertBook_Click(object sender, EventArgs e)
        {
            if (user != null)
            {
                using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                {
                    bool result = false;
                    Book book = new Book();

                    book.IdBook = Guid.NewGuid();

                    book.Title = txtTitle.Text.Trim();
                    book.Author = txtAuthors.Text.Trim();
                    book.PublishingHouse = txtPublishingHouse.Text.Trim();
                    book.Edition = txtEdition.Text.Trim();

                    CultureInfo oldCulture = CultureInfo.CurrentUICulture;
                    CultureInfo newCulture = new CultureInfo("it-IT");

                    try
                    {
                        Thread.CurrentThread.CurrentUICulture = newCulture;


                        decimal price = 0;
                        string bookPrice = txtSellingPrice.Text.Trim();
                        bool convertionSuccessfully = Decimal.TryParse(bookPrice, out price);

                        if (convertionSuccessfully)
                        {
                            book.SellingPrice = price;
                        }

                        book.SellingPrice = price; //Convert.ToDecimal(txtSellingPrice.Text.Trim().Replace(".", ","));
                    }
                    finally
                    {
                        Thread.CurrentThread.CurrentUICulture = oldCulture;
                    }

                    book.Note = txtNote.Text.Trim();

                    book.UserId = user.IdUser;

                    // CHECK: questi 2 campi potrebbero non servire visto che adesso ho il riferimento all'utente venditore
                    if (!ddlUniversity.SelectedItem.Value.Equals("0"))
                    {
                        book.UniversityId = new Guid(ddlUniversity.SelectedItem.Value);
                        if (!ddlFaculty.SelectedItem.Value.Equals("0"))
                        {
                            book.FacultyId = new Guid(ddlFaculty.SelectedItem.Value);
                        }
                    }

                    book.InsertDate = DateTime.Now;

                    // TODO: rimuovere questa property se non gestiamo lo stato del libro (Usato | Nuovo)
                    book.BookStatusId = new Guid("7235e37a-c399-11e1-965f-c9966188709b"); // Stato del Libro (dafault): USATO

                    book.CoverImage = hfCoverImagePath.Value;

                    try
                    {
                        result = service.insertBook(book);
                        Utility.Lucene_NET.LuceneFacade.AddBookToIndex(book);
                    }
                    catch (Exception ex)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "Errore!", "alert('" + ex.Message + "');", true);
                    }


                    if (result)
                    {
                        Utility.Mail.MailSender mailSender = new Utility.Mail.MailSender();
                        mailSender.SendMail(user.Email, "Annuncio inserito", "Hai messo in vendita il libro " + book.Title + ".", true);
                        pnlInsertBook.Visible = false;
                        pnlInsertBookSuccessfullyCompleted.Visible = true;
                    }
                    else
                    {
                        // TODO: creare pannello di errore per l'inserimento libro
                    }
                }
            }
        }

        protected void btnUpdateBook_Click(object sender, EventArgs e)
        {
            bool result = false;
            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                Book book = new Book();

                book.IdBook = new Guid(idBook);

                book.Title = txtTitle.Text.Trim();
                book.Author = txtAuthors.Text.Trim();
                book.PublishingHouse = txtPublishingHouse.Text.Trim();
                book.Edition = txtEdition.Text.Trim();

                CultureInfo oldCulture = CultureInfo.CurrentUICulture;
                CultureInfo newCulture = new CultureInfo("it-IT");

                try
                {
                    Thread.CurrentThread.CurrentUICulture = newCulture;


                    decimal price = 0;
                    string bookPrice = txtSellingPrice.Text.Trim();
                    bool convertionSuccessfully = Decimal.TryParse(bookPrice, out price);

                    if (convertionSuccessfully)
                    {
                        book.SellingPrice = price;
                    }

                    book.SellingPrice = price; //Convert.ToDecimal(txtSellingPrice.Text.Trim().Replace(".", ","));
                }
                finally
                {
                    Thread.CurrentThread.CurrentUICulture = oldCulture;
                }

                book.Note = txtNote.Text.Trim();

                book.UserId = user.IdUser;

                if (!ddlUniversity.SelectedItem.Value.Equals("0"))
                {
                    book.UniversityId = new Guid(ddlUniversity.SelectedItem.Value);
                    if (!ddlFaculty.SelectedItem.Value.Equals("0"))
                    {
                        book.FacultyId = new Guid(ddlFaculty.SelectedItem.Value);
                    }
                }

                // TODO: rimuovere questa property se non gestiamo lo stato del libro (Usato | Nuovo)
                book.BookStatusId = new Guid("7235e37a-c399-11e1-965f-c9966188709b"); // Stato del Libro (dafault): USATO

                book.CoverImage = hfCoverImagePath.Value;

                try
                {
                    result = service.updateBook(book);
                }
                catch (Exception ex)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "Errore!", "alert('" + ex.Message + "');", true);
                }

                if (result)
                {
                    pnlInsertBook.Visible = false;
                    pnlUpdateBookSuccessfullyCompleted.Visible = true;
                }
                else
                {
                    // TODO gestire pannello di errore dell'aggiornamento del libro
                }
            }
        }

        private string GetFilePath()
        {
            // - Recuperare la cartella del server dove verranno conservate tutte le immagini
            string ext = Path.GetExtension(CoverImageFileUpload.FileName);
            string hashName = Utility.Utility.hash(Path.GetFileName(CoverImageFileUpload.FileName) + this.user.Username + DateTime.Now.ToString());
            string destination = Server.MapPath(bookImageDirectory) + hashName + ext;
            hfCoverImagePath.Value = destination;

            return destination;
        }

        protected void btnFileupload_Click(object sender, EventArgs e)
        {
            
            // string destination = GetFilePath();

            // Make some validatins check (control have file or extension check...)
            int width = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["WidthInPixel"]);
            int height = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["HeightInPixel"]);

            // Do the resize, and save the file with desired name
            using (Bitmap img = Utility.Utility.ResizeImage(new Bitmap(CoverImageFileUpload.PostedFile.InputStream), width, height, ResizeOptions.MaxWidthAndHeight))
            {
                string ext = Path.GetExtension(CoverImageFileUpload.FileName);
                string hashName = Utility.Utility.hash(Path.GetFileName(CoverImageFileUpload.FileName) + this.user.Username + DateTime.Now.ToString());
                string destination = Server.MapPath(bookImageDirectory) + hashName + ext;
                switch (Path.GetExtension(CoverImageFileUpload.FileName).ToLower())
                {
                    case ".gif":
                        img.Save(destination, System.Drawing.Imaging.ImageFormat.Gif);
                        break;
                    case ".jpg":
                        img.Save(destination, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                    case ".png":
                        img.Save(destination, System.Drawing.Imaging.ImageFormat.Png);
                        break;
                    default:
                        img.Save(destination, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                }

                hfCoverImagePath.Value = destination;
                HideComponentAfterUpload();
                
                // Far vedere alla fine dell'upload l'immagine in anteprima
                string fileName = Path.GetFileName(destination);
                PreviewBookImage.ImageUrl = bookImageDirectory + fileName;
            }
        }

        private void HideComponentAfterUpload()
        {           
            pnlCoverUpload.Visible = false;
            pnlPreview.Visible = true;
        }

        private void EnablePreview()
        {
            pnlCoverUpload.Visible = true;
            pnlPreview.Visible = false;            
        }

        protected void ResetUploadCover_Click(object sender, EventArgs e)
        {
            EnablePreview();
        }

        protected void btnAnnulla_Click(object sender, EventArgs e)
        {
            ClearFields();
        }

        private void ClearFields()
        {
            txtTitle.Text = "";
            txtAuthors.Text = "";
            txtPublishingHouse.Text = "";
            txtEdition.Text = "";
            txtNote.Text = "";
            txtSellingPrice.Text = "";
            ddlUniversity.SelectedIndex = 0;
            ddlFaculty.SelectedIndex = 0;
        }       

    }
}